package com.yimi.yinhepda.views.unload_module.palletbind;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.SingleUnBindAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.base.BaseTitleActivity;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.entity.bean.StatForkliftTaskDetail;
import com.yimi.yinhepda.entity.bean.StatForkliftTaskDetailIndex;
import com.yimi.yinhepda.entity.request.ForkliftDetailVos;
import com.yimi.yinhepda.entity.request.PalletBindRequest;
import com.yimi.yinhepda.entity.response.AreaCodeAndNextStationResponse;
import com.yimi.yinhepda.entity.response.SuccessResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.utils.UcWaybillValidate;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.pda.ym.utils.Constants.getPalletTaskNo;

/**
 * 单独绑定界面
 *
 * @author xionggaosheng
 */
public class SingleUnBindActivity extends BaseTitleActivity implements CommonViewHolder.onItemCommonClickListener {
    /**
     * 列表
     */
    private RecyclerView listView;
    /**
     * 返回bar
     */
    private ImageButton ibBack;
    /**
     * 提交按钮
     */
    private Button btnCommit;
    /**
     * 主单数据（列表数据）集合
     */
    List<StatForkliftTaskDetail> dataList = new ArrayList<>();
    /**
     * 子单数据集合
     */
    List<StatForkliftTaskDetailIndex> childWayBillList = new ArrayList<>();
    /**
     * 适配器
     */
    private SingleUnBindAdapter adapter;

    public SingleUnBindActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "单独绑定";
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_single_un_bind;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listView = findViewById(R.id.rv_task_no);
        ibBack = findViewById(R.id.ib_back);
        btnCommit = findViewById(R.id.btn_commit);

        btnCommit.setOnClickListener(this);
        ibBack.setOnClickListener(this);
    }


    /**
     * 获得列表数据
     */
    public List<StatForkliftTaskDetail> getWaybillListData(List<StatForkliftTaskDetailIndex> childWayBillList) {
        List<StatForkliftTaskDetail> data = new ArrayList<>();
        List<String> waybillList = new ArrayList<>();
        for (StatForkliftTaskDetailIndex statForkliftTaskDetailIndex : childWayBillList) {
            if (!waybillList.contains(statForkliftTaskDetailIndex.getWaybillNo())) {
                StatForkliftTaskDetail bean = new StatForkliftTaskDetail();
                bean.setNum(1);
                bean.setNextDept(statForkliftTaskDetailIndex.getNextDept());
                bean.setNextDeptCode(statForkliftTaskDetailIndex.getNextDeptCode());
                bean.setAreaCode(statForkliftTaskDetailIndex.getAreaCode());
                bean.setWaybillNo(statForkliftTaskDetailIndex.getWaybillNo());

                data.add(bean);
                waybillList.add(statForkliftTaskDetailIndex.getWaybillNo());
            } else {
                for (StatForkliftTaskDetail datum : data) {
                    if (datum.getWaybillNo().equals(statForkliftTaskDetailIndex.getWaybillNo())) {
                        datum.setNum(datum.getNum() + 1);
                    }

                }
            }
        }
        return data;
    }


    @Override
    protected void handleBarCode(final String result) {
        if (result == null) {
            showToast("运单扫描失败");
        } else if (!StringUtils.isWaybillNo(result) && !UcWaybillValidate.validate(result)) {
            showToast("单号不规范！(" + result + ")");
        } else {

            for (StatForkliftTaskDetailIndex statForkliftTaskDetailIndex : childWayBillList) {
                if (result.equals(statForkliftTaskDetailIndex.getChildWaybillNo())) {
                    showToast("单号已扫描(" + result + ")");
                    return;
                }
            }

            Map map = new HashMap<String, String>(1);
            map.put("waybillNo", BindUtil.getWaybillNoByScanResult(result));

            showPgDlg("数据请求中...");

            new NetRequest().setMethod(NetRequest.Method.GET)
                    .setUrl(BindUtil.getQueryAreaCodeUrl(result))
                    .setParams(map)
                    .setResponsClazz(AreaCodeAndNextStationResponse.class)
                    .setConnTimeOut(10 * 1000)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            if (msg != null) {
                                showToast(msg);
                            } else {
                                showToast("服务器出错了!");
                            }
                            SoundVibratorManager.playSound(2);
                            dismissPgDlg();
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            dismissPgDlg();
                            AreaCodeAndNextStationResponse response = (AreaCodeAndNextStationResponse) obj;
                            if (response.isSuccess()) {
                                if (response.getData() != null) {
                                    StatForkliftTaskDetailIndex bean = new StatForkliftTaskDetailIndex();
                                    bean.setChildWaybillNo(result);
                                    bean.setWaybillNo(BindUtil.getWaybillNoByScanResult(result));
                                    bean.setAreaCode(response.getData().getStorageCode() == null ? "" : response.getData().getStorageCode());
                                    bean.setNextDept(response.getData().getNextDeptName() == null ? "" : response.getData().getNextDeptName());
                                    bean.setNextDeptCode(response.getData().getNextDeptCode() == null ? "" : response.getData().getNextDeptCode());

                                    childWayBillList.add(bean);
                                    dataList.clear();
                                    dataList.addAll(getWaybillListData(childWayBillList));
                                    loadUIAdapter();
                                    SoundVibratorManager.playSound(1);
                                } else {
                                    showToast("无运单信息！");
                                    SoundVibratorManager.playSound(2);
                                }
                            }
                        }
                    });
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_back:
                finish();
                break;

            case R.id.btn_commit:
                //提交请求
                submitRequest();
                break;
        }
    }


    /**
     * 提交请求
     */
    private void submitRequest() {
        showPgDlg("正在提交...");
        final String palletTaskNo = getPalletTaskNo();

        final PalletBindRequest palletBindRequest = new PalletBindRequest();
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                List<ForkliftDetailVos> forkliftDetailVos = new ArrayList<>();
                for (StatForkliftTaskDetailIndex entity : childWayBillList) {
                    ForkliftDetailVos detailVos = new ForkliftDetailVos();
                    detailVos.setWaybillNo(entity.getWaybillNo());
                    detailVos.setChildWaybillNo(entity.getChildWaybillNo());
                    detailVos.setAreaCode(entity.getAreaCode());
                    detailVos.setNextDeptCode(entity.getNextDeptCode());
                    detailVos.setNextDept(entity.getNextDept());
                    //PDA 输入
                    detailVos.setInputType(1);
                    detailVos.setForkliftNo(palletTaskNo);
                    //叉车分货
                    detailVos.setScanType(2);
                    detailVos.setCancleStatu(1);
                    detailVos.setStowageNo(entity.getStowageNo());
                    detailVos.setOperTime(DateHelper.getDateTimeFormateForSimple(new Date()));
                    detailVos.setBandType(2);
                    detailVos.setType(detailVos.getWaybillNoType());
                    forkliftDetailVos.add(detailVos);
                }

                palletBindRequest.setForkliftDetailVos(forkliftDetailVos);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                if (palletBindRequest.getForkliftDetailVos().isEmpty()) {
                    dismissPgDlg();
                    showToast("无扫描数据不可提交！");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                        .setUrl(Constants.URL_BIND_FORFLIFT)
                        .setRequestObject(palletBindRequest)
                        .setResponsClazz(SuccessResponse.class)
                        .execute(new UICallBack() {
                            @Override
                            public void onError(String msg) {
                                SoundVibratorManager.playSound(2);
                                dismissPgDlg();
                                showToast(msg);
                            }

                            @Override
                            public void onSuccess(Object obj) {
                                SoundVibratorManager.playSound(1);
                                dismissPgDlg();
                                SuccessResponse successResponse = (SuccessResponse) obj;
                                if (successResponse.isSuccess()) {
                                    showToast("单独绑定成功");
                                    childWayBillList.clear();
                                    dataList.clear();
                                    loadUIAdapter();
                                    finish();
                                }
                            }
                        });
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    private void loadUIAdapter() {
        if (adapter == null) {
            adapter = new SingleUnBindAdapter(this, dataList, this);
            listView.setLayoutManager(new LinearLayoutManager(this));
            listView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClickListener(int position) {

    }

    @Override
    public void onItemLongClickListener(int position) {

    }


    @Override
    public boolean showBack() {
        return true;
    }

    @Override
    public void setBack() {
        finish();
    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
